package com.anxin.registerManagement.service;

import cn.hutool.core.util.ObjectUtil;
import com.anxin.registerManagement.bean.jo.LogSearchJo;
import com.anxin.registerManagement.bean.persist.LogInfo;
import com.anxin.registerManagement.bean.persist.User;
import com.anxin.registerManagement.mapper.LogInfoMapper;
import com.anxin.registerManagement.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 叶前呈
 * @date 2022/3/27 13:43
 */
@Service
public class LogService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogService.class);

    @Autowired
    LogInfoMapper logInfoMapper;

    @Autowired
    UserMapper userMapper;

    public PageInfo<LogInfo> searchLog(LogSearchJo logSearchJo) {
        PageHelper.startPage(logSearchJo.getPageNum(), logSearchJo.getPageSize());
        LambdaQueryWrapper<LogInfo> logInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtil.isEmpty(logSearchJo.getHandleName())) {
            logInfoLambdaQueryWrapper.like(LogInfo::getHandleName, logSearchJo.getHandleName());
        }
        List<LogInfo> logInfos = new ArrayList<>();
        if (!ObjectUtil.isEmpty(logSearchJo.getHandleUserName())) {
            // 通过名称查询id
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.like(User::getNickName, logSearchJo.getHandleUserName());
            List<Integer> userIdList = userMapper.selectObjs(userLambdaQueryWrapper).stream().map(o -> (Integer) o).collect(Collectors.toList());
            // 这里的逻辑应该是，如果查不到人，就是应该返回空数据
            if (userIdList.size() > 0) {
                logInfoLambdaQueryWrapper.in(LogInfo::getHandleUserId, userIdList);
            }else {
                return new PageInfo<>(logInfos);
            }
        }
        logInfos = logInfoMapper.selectList(logInfoLambdaQueryWrapper);
        return new PageInfo<>(logInfos);
    }

}
